package com.fsbm.ctech.maxis.ebpsbackend;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.lowagie.text.Annotation;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class PDFUtil {
	public static void main(String[] args) throws Exception {
		//PDF("bill.pdf", "new_bil.pdf", "http://maxis.com.my");
		InputStream instr = new FileInputStream("bill.pdf");
		 OutputStream outstr        = new FileOutputStream("new_bill.pdf");
		byte[] buffer = new byte[262144];
		int size      = 0;
        AddIcon(instr, outstr, "maxispay_paynow_icons.png", "http://maxis.com.my");
        while ((size  = instr.read(buffer, 0, buffer.length)) != -1) {
			outstr.write(buffer, 0, size);
		}
		instr.close();
		outstr.flush();
		outstr.close();
	}
	
	public static InputStream AddIcon(InputStream instr, OutputStream outStr, String iconFile, String href) throws IOException, DocumentException{
		PdfReader pdfReader = new PdfReader(instr);
        
        PdfStamper pdfStamper = new PdfStamper(pdfReader, outStr);

        Image image = Image.getInstance(iconFile);
        image.setAbsolutePosition(313f, 570f);
        image.scaleToFit(60, 60);
        image.setAnnotation(new Annotation(0, 0, 0, 0, href));
        for(int i=1; i<= pdfReader.getNumberOfPages(); i++){
            PdfContentByte content = pdfStamper.getOverContent(i);
            if(i == 1) {
            	content.addImage(image);
            }
        }
        pdfStamper.close();
        return instr;
	}
}
